package tv.youxing.android.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;
import com.kymjs.rxvolley.http.VolleyError;
import com.lljjcoder.citypickerview.widget.CityPicker;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import tv.youxing.android.R;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.entity.DianZhanModel;
import tv.youxing.android.entity.ThisLloginUserInfo;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.L;
import tv.youxing.android.utils.ShareUtils;
import tv.youxing.android.utils.StaticClass;
import tv.youxing.android.utils.UtilTools;

import static com.mob.MobSDK.getContext;


/**
 * 编辑个人资料
 */
public class MyInfoEditActivity extends BaseActivity {


    Toolbar mToolbar;


    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.male)
    RadioButton male;
    @BindView(R.id.female)
    RadioButton female;
    @BindView(R.id.rg_sex)
    RadioGroup rgSex;
    @BindView(R.id.age)
    TextView age;
    @BindView(R.id.et_age)
    EditText etAge;
    @BindView(R.id.constellation)
    TextView constellation;
    @BindView(R.id.et_constellation)
    EditText etConstellation;
    @BindView(R.id.School)
    TextView School;
    @BindView(R.id.et_school)
    EditText etSchool;
    @BindView(R.id.location)
    TextView location;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.ll_location_selected)
    RelativeLayout ll_location_selected;
    @BindView(R.id.resume)
    EditText etResume;
    @BindView(R.id.commit)
    Button btnPost;//提交


    boolean is_male = true;//性别判断 默认为男

    //省市区
    String province="";
    String city="";
    String area="";
    private ThisLloginUserInfo mAlldata;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_info_edit);
        ButterKnife.bind(this);


        initView();
        loadData();



        btnPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String name = UtilTools.getString(etName);
                String ageStr = UtilTools.getString(etAge);

                if (name.equals("")) {
                    CustomToast.INSTANCE.showToast("昵称不能为空");
                    return;
                }

                int age = 0;
                if (!UtilTools.getString(etAge).equals("")) {
                    age = Integer.parseInt(UtilTools.getString(etAge));
                }
                int sex = 1;
                if (is_male) {
                    sex = 1;
                } else {
                    sex = 0;
            }
            String constellation = UtilTools.getString(etConstellation);
            String school = UtilTools.getString(etSchool);
            //                String location = UtilTools.getString(etLocation);
            String resume = UtilTools.getString(etResume);



                    HttpParams params = new HttpParams();
                    params.putHeaders("Authorization","Bearer "+ ShareUtils.getString(getContext(), AppConst.TOKEN,""));

                if (!ageStr.equals("")) {
                    params.put("age",age);
                }

                    params.put("sex",sex);
                    params.put("username",name);

                if (!constellation.equals("")) {
                    params.put("constellation", constellation);
                }

                if (!school.equals("")) {
                    params.put("school", school);
                }


                if (!province.equals("")) {
                    params.put("province",province);//省
                }
                if (!city.equals("")) {
                    params.put("city",city);//市
                }
                if (!area.equals("")) {
                    params.put("area",area);//区
                }

                if (!resume.equals("")){
                    params.put("sign",resume);//个人简历
                }



                        RxVolley.post(StaticClass.MyInfoEdit, params, new HttpCallback() {
                            @Override
                            public void onSuccess(String t) {
                                DianZhanModel dianZhanModel = GsonUtils.GsonToBean(t, DianZhanModel.class);

                                if (dianZhanModel.getCode() == AppConst.TOKENERROR) {
                                    MyInfoEditActivity.this.startActivity(new Intent(MyInfoEditActivity.this,LoginActivity.class));
                                    return;
                                }

                                CustomToast.INSTANCE.showToast(dianZhanModel.getStatus());


                                if (dianZhanModel.getCode() == 200) {
                                    finish();
                                } else {
                                    L.d(t);
                                }
                            }
                        });
            }
        });
    }

    private void initView() {
        rgSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                switch (rgSex.getCheckedRadioButtonId()) {
                    case R.id.female://女
                        is_male = false;
                        break;
                    case R.id.male://男
                        is_male = true;
                        break;
                }

            }
        });
    }


    void loadData() {
        showProgress("加载中");
        HttpParams params = new HttpParams();
        params.put("user_id",ShareUtils.getInt(this,AppConst.USERID,-1));
        params.putHeaders("Authorization","Bearer "+ ShareUtils.getString(getContext(),AppConst.TOKEN,""));

        RxVolley.post(StaticClass.thisLoginUserInfo, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                mAlldata = GsonUtils.GsonToBean(t,ThisLloginUserInfo.class);


                if (mAlldata.getCode() == AppConst.TOKENERROR) {
                    MyInfoEditActivity.this.startActivity(new Intent(MyInfoEditActivity.this,LoginActivity.class));
                    return;
                }

                hideProgress();
                updateInfo();
            }

            @Override
            public void onFailure(VolleyError error) {
                super.onFailure(error);
                hideProgress();
            }
        });
    }


    void updateInfo() {

        ThisLloginUserInfo.ResultBean h = mAlldata.getResult();

        etName.setText(h.getUser_info().getUsername());
        if (h.getUser_info().getSex() == 1) {
            male.setChecked(true);
            is_male=true;
        } else {
            is_male=false;
            female.setChecked(true);
        }
        etAge.setText(h.getUser_info().getAge()+"");
        etConstellation.setText(h.getUser_info().getConstellation());
        etSchool.setText(h.getUser_info().getSchool());
        tvLocation.setText(h.getUser_info().getProvince()+" "+h.getUser_info().getCity() + " " +h.getUser_info().getArea());
        etResume.setText(h.getUser_info().getSign());

        province = h.getUser_info().getProvince();
        city = h.getUser_info().getCity();
        area = h.getUser_info().getArea();


    }

    @OnClick({R.id.ll_location_selected})
    public void click(View view) {

        switch (view.getId()) {
            case R.id.ll_location_selected://地区选择
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);



                CityPicker cityPicker = new CityPicker.Builder(MyInfoEditActivity.this)
                        .textSize(20)
                        .title("地址选择")
                        .backgroundPop(0xa0000000)
                        .titleBackgroundColor("#ffffff")
                        .titleTextColor("#000000")
                        .backgroundPop(0xa0000000)
                        .confirTextColor("#000000")
                        .cancelTextColor("#000000")
                        .province("福建省")
                        .city("厦门市")
                        .district("湖里区")
                        .textColor(Color.parseColor("#000000"))
                        .provinceCyclic(true)
                        .cityCyclic(false)
                        .districtCyclic(false)
                        .visibleItemsCount(7)
                        .itemPadding(10)
                        .onlyShowProvinceAndCity(false)//true 设置二级联动 false 三级联动
                        .build();
                cityPicker.show();

                //监听方法，获取选择结果
                cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
                    @Override
                    public void onSelected(String... citySelected) {
                        //省份
                        String province = citySelected[0];
                        //城市
                        String city = citySelected[1];
                        //区县（如果设定了两级联动，那么该项返回空）
                        String district = citySelected[2];
                        //邮编
                        String code = citySelected[3];


                        MyInfoEditActivity.this.province = province;
                        MyInfoEditActivity.this.city = city;
                        MyInfoEditActivity.this.area = district;

                        tvLocation.setText(province+" "+city+" "+district);

                    }

                    @Override
                    public void onCancel() {
                        Toast.makeText(MyInfoEditActivity.this, "已取消", Toast.LENGTH_LONG).show();
                    }
                });
                break;
        }
    }
}
